package com.jy.wms.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.Page;
import com.joyi.gate.comm.SessionInfo;
import com.joyi.gate.safety.vo.UserInfo;
import com.jy.wms.common.SetStatus;
import com.jy.wms.common.UUIDUtils;
import com.jy.wms.common.base.*;
import com.jy.wms.pojo.*;
import com.jy.wms.service.WmsOwnerSupplierService;
import com.jy.wms.service.WmsPurchaseOrderService;
import com.jy.wms.service.WmsTurnoverRuleMiddleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: WmsPurchaseOrderController
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @Author lh
 * @Date Fri Sep 15 17:36:50 GMT+08:00 2017
 */

@RestController
@RequestMapping("/wmsPurchaseOrder")
@Api(value = "/wmsPurchaseOrder", description = "关于采购订单操作")
public class WmsPurchaseOrderController extends BaseController<WmsPurchaseOrderService, WmsPurchaseOrder> {

    @Autowired
    private WmsOwnerSupplierService wmsOwnerSupplierService;

    @ApiOperation(value = "查询列表", response = JSONObject.class, notes = "查询列表")
    @PostMapping(value = "/list")
    public
    @ResponseBody
    JSONObject getWmsPurchaseOrder(@RequestBody WmsPurchaseOrder entity, HttpSession session) {
        JSONObject json = getJSONObject();
        UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);//用户信息
        String ckid = String.valueOf(userinfo.getUser().getOrgId().get(0));//仓库id
        String ckmc = userinfo.getUser().getOrgName();//仓库名称
        String hzid = null;
        String gysid = null;
        List<SysHz> hz = (List) session.getAttribute(BaseSessionInfo.SessionConsignor);//货主
        if (hz.size() > 0) {
            hzid = hz.get(0).getHzid();
        }
        List<SysGys> gys = (List) session.getAttribute(BaseSessionInfo.SessionGys);//供应商
        if (gys != null && gys.size() > 0) {
            gysid = gys.get(0).getGysid();
        }
        entity.setSsck(ckmc);
        Page<WmsPurchaseOrder> list = null;
        if ((hzid != "" && hzid != null && gysid != "" && gysid != null) || (hzid != "" && hzid != null && (gysid == "" || gysid == null))) {//仓库管理员/操作员仓库
            list = baseService.baseSelectPage(entity, hzid, "", ckid);

        } else if ((hzid == "" || hzid == null) && gysid != "" && gysid != null) {//供应商操作员
            list = baseService.baseSelectPage(entity, "", gysid, ckid);
        }
        return json = SetStatus.setSearchType(JSONArray.fromObject(list).toString(), (int) list.getTotal());
    }

    @ApiOperation(value = "获取供应商", response = JSONObject.class, notes = "获取货主所对应的供应商")
    @GetMapping(value = "/getWmsOwnerSupplierByHzid")
    public
    @ResponseBody
    JSONArray getWmsOwnerSupplierByHzid(HttpSession session) {

        UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);//用户信息
        String ckid = String.valueOf(userinfo.getUser().getOrgId().get(0));//仓库id
        String hzid = null;
        String gysid = null;
        /*
        （1）使用角色为仓库操作员/仓库管理员，新增采购订单时只能选择当前操作货主下的供应商。
        （2）使用角色为供应商操作员，新增采购订单时供应商为当前账户操作的供应商。
        */
        List<SysHz> hz = (List) session.getAttribute(BaseSessionInfo.SessionConsignor);//货主
        if (hz.size() > 0) {
            hzid = hz.get(0).getHzid();
            hz.get(0).getShow_hzid();
        }
        List<SysGys> gys = (List) session.getAttribute(BaseSessionInfo.SessionGys);//供应商
        if (gys != null && gys.size() > 0) {
            gysid = gys.get(0).getGysid();
        }
        List<WmsOwnerSupplier> list = null;
        try {
            if ((hzid != "" && hzid != null && gysid != "" && gysid != null) || (hzid != "" && hzid != null && (gysid == "" || gysid == null))) {//仓库管理员//仓库操作员
                list = baseService.getWosByHzid(hzid, ckid);
            } else if ((hzid == "" || hzid == null) && gysid != "" && gysid != null) {//供应商操作员
                WmsOwnerSupplier wmsOwnerSupplier = baseService.getSupplier(gysid, ckid);
                list.add(wmsOwnerSupplier);
            }

        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return JSONArray.fromObject(list);
    }

    @ApiOperation(value = "生成订单编号", response = JSONObject.class, notes = "生成订单编号，'gysbh'供应商编号")
    @PostMapping(value = "/getBh/{gysbh}")
    public
    @ResponseBody
    JSONObject getBh(@PathVariable("gysbh") String gysbh) {
        JSONObject json = getJSONObject();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
        String bh = gysbh + df.format(new Date());
        json.put("bh", bh);
        return json;
    }

    @ApiOperation(value = "获取订单类型字典", response = JSONObject.class, notes = " 查询输入</br>{\"ddlx\":\"订单类型名称名称模糊查询\"}")
    @PostMapping(value = "getPoLx")
    public @ResponseBody
    JSONArray getPoLx(HttpSession session, @RequestBody Map<String, String> map) {
        List<WmsOwnerOrdertype> list = null;
        try {
            //用户信息
            UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            String ckid = String.valueOf(userinfo.getUser().getOrgId().get(0));//仓库id
            List<SysHz> hz = (List) session.getAttribute(BaseSessionInfo.SessionConsignor);
            String hzid = null;
            if (hz.size() > 0) {
                hzid = hz.get(0).getHzid();
                list = baseService.getPoLx(hzid, ckid, map.get("ddlx"));
            }
        } catch (ServiceException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSONArray.fromObject(list);
    }

    @ApiOperation(value = "获取供应商对应的货品", response = JSONObject.class, notes = "获取供应商对应的货品 查询输入</br>{\"bh\":\"货品编号模糊查询\",\"gysid\":\"供应商id\"}")
    @PostMapping(value = "getGoods")
    public @ResponseBody
    JSONArray getGoods(HttpSession session, @RequestBody Map<String, String> map) {

        List<WmsPurchaseOrder> list = null;
        try {
            UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);//用户信息
            String ckid = String.valueOf(userinfo.getUser().getOrgId().get(0));//仓库id
            list = baseService.getGoods(map.get("gysid"), ckid, map.get("bh"));
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return JSONArray.fromObject(list);
    }


    @ApiOperation(value = "根据包装id查找包装明细(获取主单位用)", response = JSONObject.class, notes = "根据包装id查找包装明细，bzid：包装id")
    @GetMapping(value = "packDetailList/{bzid}")
    public @ResponseBody
    JSONArray packDetailList(@PathVariable String bzid, HttpSession session) {
        List<WmsPackingDetailed> list = null;
        try {
            UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);//用户信息
            String ckid = String.valueOf(userinfo.getUser().getOrgId().get(0));//仓库id
            list = baseService.packDetailList(bzid, ckid);
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return JSONArray.fromObject(list);
    }

    @ApiOperation(value = "订单添加", response = JSONObject.class, notes = "添加采购订单")
    @PostMapping(value = "add")
    public @ResponseBody
    JSONObject addWmsPurchaseOrder(@RequestBody WmsPurchaseOrder entity, HttpSession session) {
        entity.setId(UUIDUtils.uuid());
        //用户信息
        UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
        String ckid = String.valueOf(userinfo.getUser().getOrgId().get(0));//仓库id
        List<SysHz> hz = (List) session.getAttribute(BaseSessionInfo.SessionConsignor);
        List<SysGys> gys = (List) session.getAttribute(BaseSessionInfo.SessionGys);//供应商
        String hzid = null;
        String gysid = null;

        String lx = userinfo.getUser().getShow_type();
        entity.setCkid(ckid);
        entity.setCjr(userinfo.getUser().getName());
        entity.setXgr(userinfo.getUser().getName());

        try {
            if (hz.size() > 0) {
                hzid = hz.get(0).getHzid();
            } else {
                if (gys != null && gys.size() > 0) {
                    gysid = gys.get(0).getGysid();
                    EntityWrapper ew = new EntityWrapper();
                    ew.setEntity(new WmsOwnerSupplier());
                    ew.where("id={0}", gysid);
                    WmsOwnerSupplier wmsOwnerSupplier = (WmsOwnerSupplier) wmsOwnerSupplierService.selectObj(ew);
                    hzid = wmsOwnerSupplier.getSshzid();
                }
            }
            entity.setHzid(hzid);
            baseService.baseInsert(entity, lx);
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(), "采购订单增加成功", "", JSONObject.fromObject(entity).toString());
        } catch (SucessException e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(), "采购订单增加成功", e.getMessage(), JSONObject.fromObject(entity).toString());
        } catch (ServiceException e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(), "采购订单增加失败", e.getMessage(), "");
        } catch (Exception e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(), "采购订单增加失败", e.getMessage(), "");
        }

    }


    @ApiOperation(value = "采购订单编辑", response = JSONObject.class, notes = "编辑采购订单")
    @PostMapping(value = "edit")
    public @ResponseBody
    JSONObject editWmsPurchaseOrder(@RequestBody WmsPurchaseOrder entity, HttpSession session) {
        UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);//用户信息
        entity.setXgr(userinfo.getUser().getName());
        try {
            baseService.baseUpdateByPrimaryKeySelective(entity);
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(), "采购订单修改成功", "", "");
        } catch (SucessException e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(), "采购订单修改成功", e.getMessage(), "");
        } catch (ServiceException e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(), "采购订单修改失败", e.getMessage(), "");
        } catch (Exception e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(), "采购订单修改失败", e.getMessage(), "");
        }
    }

    @ApiOperation(value = "编辑时查找对象", response = JSONObject.class, notes = "编辑时查找对象,id:采购订单id")
    @GetMapping(value = "getOrderAndDetail/{id}")
    public @ResponseBody
    JSONObject getOrderAndDetail(@PathVariable String id) {
        JSONObject jsonObject = null;
        try {
            jsonObject = baseService.baseSelectByPrimaryKey(id);
        } catch (ServiceException e) {
            e.printStackTrace();
            // return SetStatus.setReturn(0, false, 1, "查找采购订单及明细", e.getMessage(), "");
        } catch (Exception e) {
            e.printStackTrace();
            //   return SetStatus.setReturn(0, false, 1, "查找采购订单及明细", "查找采购订单及明细", "");
        }
        return jsonObject;
    }


    @ApiOperation(value = "删除采购订单", response = JSONObject.class, notes = "采购订单删除，ids:选中的多条采购订单的id集合")
    @PostMapping(value = "delete")
    public @ResponseBody
    JSONObject deleteWmsPurchaseOrder(@RequestBody SetAndModifyModel setModel, HttpSession session) {
        UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);//用户信息
        try {
            baseService.baseDeleteBathPrimaryKeys(setModel.getIds(), userinfo.getUser().getName());
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(), "采购订单删除成功", "", "");

        } catch (SucessException e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(), "采购订单删除成功", e.getMessage(), "");

        } catch (ServiceException e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(), "采购订单删除失败", e.getMessage(), "");

        } catch (Exception e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(), "采购订单删除失败", e.getMessage(), "");
        }
    }


    @ApiOperation(value = "审核采购订单", response = JSONObject.class, notes = "采购订单审核,ids:选中的多条采购订单的id集合")
    @PostMapping(value = "updateShzt")
    public @ResponseBody
    JSONObject updateShzt(@RequestBody SetAndModifyModel setModel, HttpSession session) {
        UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);//用户信息
        try {
            baseService.updateShzt(setModel.getIds(), userinfo.getUser().getName());
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(), "采购订单审核成功", "", "");
        } catch (SucessException e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(), "采购订单审核成功", e.getMessage(), "");

        } catch (ServiceException e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(), "采购订单审核失败", e.getMessage(), "");
        } catch (Exception e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(), "采购订单审核失败", e.getMessage(), "");
        }
    }

    @ApiOperation(value = "标记收货完成", response = JSONObject.class, notes = "标记收货完成,ids:选中的多条采购订单的id集合")
    @PostMapping(value = "updateZt")
    public @ResponseBody
    JSONObject updateZt(@RequestBody SetAndModifyModel setModel, HttpSession session) {
        //   SysUser user=(SysUser)getSessionInfo(SessionInfo.SessionName);
        UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);//用户信息
        try {
            baseService.updateZt(setModel.getIds(), userinfo.getUser().getName());
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(), "标记完成", "", "");
        } catch (SucessException e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(), "标记完成", e.getMessage(), "");
        } catch (ServiceException e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(), "标记失败", e.getMessage(), "");
        } catch (Exception e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(), "标记失败", e.getMessage(), "");
        }
    }


    @ApiOperation(value = "导出采购订单及明细", response = JSONObject.class, notes = "导出采购订单及明细")
    @PostMapping(value = "getOutPutList")
    public JSONObject getOutPutList(HttpServletResponse response, @RequestBody Map map, HttpSession session) throws IOException {
        String cjsj_start = (String) map.get("cjsj_start");
        String cjsj_end = (String) map.get("cjsj_end");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String start = null;
        String end = null;
        if (cjsj_start != null && cjsj_start != "") {
            long scsj_start = Long.parseLong(cjsj_start);//开始时间
            Date date1 = new Date(scsj_start);
            start = format.format(date1);
        }
        if (cjsj_end != null && cjsj_end != "") {
            long scsj_end = Long.parseLong(cjsj_end);//结束时间
            Date date2 = new Date(scsj_end);
            end = format.format(date2);
        }
        map.put("cjsj_start", start);
        map.put("cjsj_end", end);

        String filename = "采购订单导出";
        UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);//用户信息
        String ckid = String.valueOf(userinfo.getUser().getOrgId().get(0));//仓库id
        String ckmc = userinfo.getUser().getOrgName();//仓库名称
        map.put("ckid", ckid);
        List<String> ids = (List) map.get("ids");
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("采购订单表", "UTF-8") + ".xls");
        //编码
        response.setCharacterEncoding("UTF-8");
        ExportParams ep = new ExportParams();
        ep.setStyle(ManySheetOneSyler.class);
        List<WmsPurchaseOrder> list = null;
        map.put("ssck", ckmc);

        list = baseService.getOutPutList(ids, map);

        Workbook workbook = ExcelExportUtil.exportExcel(ep, WmsPurchaseOrder.class, list);
        workbook.write(response.getOutputStream());
        return null;
    }


    @ApiOperation(value = "通过供应商id获取供应对象", response = JSONObject.class, notes = "通过供应商id获取供应对象")
    @GetMapping(value = "getSupplierByGysid/{gysid}")
    public @ResponseBody
    JSONObject getSupplierByGysid(HttpSession session, @PathVariable String gysid) {
        WmsOwnerSupplier wmsOwnerSupplier = null;
        try {
            //用户信息
            UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            String ckid = String.valueOf(userinfo.getUser().getOrgId().get(0));//仓库id
            wmsOwnerSupplier = baseService.getSupplierByGysid(gysid, ckid);
        } catch (ServiceException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSONObject.fromObject(wmsOwnerSupplier);
    }

    @ApiOperation(value = "通过货品id获取货品对象", response = JSONObject.class, notes = "通过货品id获取货品对象")
    @GetMapping(value = "getGoodsByHpid/{hpid}")
    public @ResponseBody
    JSONObject getGoodsByHpid(HttpSession session, @PathVariable String hpid) {
        WmsPurchaseOrder wmsGoods = null;
        try {
            //用户信息
            UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            String ckid = String.valueOf(userinfo.getUser().getOrgId().get(0));//仓库id
            wmsGoods = baseService.getGoodsByHpid(hpid, ckid);
        } catch (ServiceException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSONObject.fromObject(wmsGoods);
    }

    @ApiOperation(value = "通过采购订单id获取订单明细集合", response = JSONObject.class, notes = "通过采购订单id获取订单明细集合")
    @GetMapping(value = "wmsPurchaseOrderDetailList/{sscgdid}")
    public @ResponseBody
    JSONArray wmsPurchaseOrderDetailList(HttpSession session, @PathVariable String sscgdid) {
        List<WmsPurchaseOrderDetailed> list = null;
        try {
            //用户信息
            UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            String ckid = String.valueOf(userinfo.getUser().getOrgId().get(0));//仓库id
            list = baseService.wmsPurchaseOrderDetailList(sscgdid);
        } catch (ServiceException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSONArray.fromObject(list);
    }

    @ApiOperation(value = "查询ASN列表", response = JSONObject.class, notes = "根据采购订单id查询ASN列表 查询输入</br>{\"ccddid\":\"采购订单 id\",\"page\":\"页\",\"rows\":\"行\"}")
    @PostMapping(value = "/getWmsEstimatedArrivalOrders")
    public
    @ResponseBody
    JSONObject getWmsEstimatedArrivalOrders(@RequestBody Map map, HttpSession session) {
        UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
        String ckid = String.valueOf(userinfo.getUser().getOrgId().get(0));//仓库id
        Page<WmsEstimatedArrivalOrder> list = null;
        list = baseService.getWmsEstimatedArrivalOrders((String) map.get("ccddid"), ckid, (Integer) map.get("page"), (Integer) map.get("rows"));
        return SetStatus.setSearchType(JSONArray.fromObject(list).toString(), (int) list.getTotal());
    }

}
